package com.puboot.common.intercepter;

import com.puboot.component.CommonDataService;
import com.puboot.module.admin.model.BizLink;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Nobita
 */
@Component
@AllArgsConstructor
public class CommonDataInterceptor implements HandlerInterceptor {

    private final CommonDataService commonDataService;


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv) throws Exception {
        if (mv != null) {
            mv.addAllObjects(commonDataService.getAllCommonData());
            List<BizLink> linkList = (List<BizLink>) mv.getModel().get("LINK_LIST");
            Map<String, List<BizLink>> linkMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(linkList)) {
                for (BizLink bizLink : linkList) {
                    List<BizLink> list = linkMap.get(bizLink.getEmail());
                    if (list == null) {
                        list = new ArrayList<>();
                        list.add(bizLink);
                        linkMap.put(bizLink.getEmail(), list);
                    } else {
                        list.add(bizLink);
                    }
                }
            }
            mv.addObject("linkListMap", linkMap);
        }
    }
}